const express =require('express');
const fs=require('fs')
let app = express()
let persons = fs.readFileSync(__dirname + '/persons.json', 'utf8')
let per = JSON.parse(persons);
let ejs = require("ejs");
//解析表单提交的数据
app.use(express.urlencoded({ extended: false }));
//ejs模板引擎显示html文件设置
app.set("view engine","html")
app.set("views",__dirname+"/view")
app.engine("html", ejs.__express);

// 加载静态资源
app.use(express.static(__dirname + "/static"));

app.get("/login", (req, res) => {
    res.render("login.html");
})
app.get("/reg", (req, res) => {
    res.render("register.html");
})
app.post('/login', (req, res) => {
    per.find(v => v.username == req.body.username && v.password == req.body.password) ? res.send("登录成功") : res.send("用户名密码错误");
})
app.post('/reg', (req, res) => {
    let onoff = per.find(val => val.username == req.body.username)
    if (onoff) {
        res.send("用户名已经被占用")
    } else {
        res.send("注册成功")
        per.push({
            "username": req.body.username,
            "password": req.body.password
        })
        fs.writeFileSync(__dirname + '/persons.json', JSON.stringify(per), { flag: "w" })
    }
})

app.listen(4000, "127.0.0.1", (req, res) => {
    console.log("启动")
})